package com.demo.juc.volat;

import java.util.concurrent.TimeUnit;

/**
 * @Author: shubin_yao
 * @Date: 2022/05/08/19:33
 * @Description: 手写单例 : 单机版
 * 问题点： 多线程下并发问题，单例失效
 * <p>
 * 解决方案：
 * 双端检测ceshi
 */
public class SingletonInstance {
    public static void main(String[] args) {
        //System.out.println(SingletonInstance.getInstance() == SingletonInstance.getInstance());

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                //SingletonInstance.getInstance();
                SingletonInstance.getInstance1();
            }, String.valueOf(i)).start();
        }

    }


    private static SingletonInstance instance = null;

    private SingletonInstance() {
        System.out.println(Thread.currentThread().getId() + "\t .......执行构造方法");
    }


    //单机版
    private static SingletonInstance getInstance() {
        if (instance == null) {
            instance = new SingletonInstance();
        }
        return instance;
    }

    //多线程环境：双端检测
    private static SingletonInstance getInstance1() {
        if (instance == null) {
            synchronized (SingletonInstance.class) {
                if (instance == null) {
                    instance = new SingletonInstance();
                }
            }
        }
        return instance;
    }

}

